package com.zyh.scs.admin.utils.jd;

import com.zyh.scs.admin.api.bo.AutoLoginParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * desc: 参数加密解密
 * project: activity
 * Created by yfliqiang@jd.com
 * 2016-12-07 10:27
 */
public class AutologinParamUtil {

    private static final Logger log = LoggerFactory.getLogger(AutologinParamUtil.class);

    /**
     * 参数加密
     *
     * @param srcStr           要加密的原始字符串
     * @param rsaEncryptPubKey 加密RSA公钥
     * @return
     */
    public static String encryptParam(String srcStr, String rsaEncryptPubKey) {
        try {
            byte[] s1Byte = RsaCoder.encryptByPublicKey(srcStr.getBytes(), rsaEncryptPubKey);
            String s1 = RsaCoder.encryptBASE64(s1Byte);
            return s1;
        } catch (Exception e) {
            System.out.println("参数加密失败,srcStr=" + srcStr);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 参数解密
     *
     * @param encryptedStr   已加密的字符串
     * @param rsaSignPrivKey 加密RSA私钥
     * @return
     */
    public static String decryptParam(String encryptedStr, String rsaSignPrivKey) {
        try {
            log.info("参数解密 encryptedStr: {}", encryptedStr);
            byte[] s1EncryptedByte = RsaCoder.decryptBASE64(encryptedStr);
            log.info("参数解密 s1EncryptedByte: {}", new String(s1EncryptedByte, StandardCharsets.UTF_8));
            byte[] s1Byte = RsaCoder.decryptByPrivateKey(s1EncryptedByte, rsaSignPrivKey);
            log.info("参数解密 s1Byte: {}", new String(s1Byte, StandardCharsets.UTF_8));
            return new String(s1Byte);
        } catch (Exception e) {
            System.out.println("参数解密失败,encryptedStr=" + encryptedStr);
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String body = "ZLZpg/Vocj0U4zgidWaOI0cXWTm3Wus0et9Cim88kfhlBvPyXqjumkyxCTpGaAULsSN9to7SzsEi" +
                "ea80EwxfLRdLf0DQXIRt2NzIDcujavK9cbP+K9BXTHlNFqHR++KTr0K3UIz/m6zfnD2VSd40phf+" +
                "qboKn9wd1uUbJUZq+Xk=";
//        String body = "HGlKCmZ2AVo5BJUjTFHGRwpOxn8soS8iEik325t072CZClRXVj+kqIsBX7IfgLiedolhU/QE3nXET3aoADqpEisbYMsK26Zt+crOaK9jkqygZBvGzrFg1nyTIX9BLcYNfzDOIJ+U47NREQJb3dKAOEbaBW8E3Nw2zK+lQpSrsyc=";
//        String body = "HeSwTLOnR/glmnMsdevIH80Cbo9ydFr0xkr5z22fPKDFu+DhU99/qqonRi/n5Ys18Yd2l/TQJjWQRRvsA2caCJkTktCWBnxeH3vwN7Gjn25dTnKVGpnm7fVHXfSt4yC1qa5dy3qgM3ofxEclB2IGK+prZFvTbWreL8w6sjOAhSI=";


        decryptParam(body,
                "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAIR87mTh8Qe5oiCJPR/eI5m57RpfkKVSaHae4QvRkdg6Lywxpw3+LjNfW1yg6sVJjHnMP1iDd6Da/xkspDUFYxK/OjH6R0u+4RaX4qTy7wMkfBxfCagCCrp7nhPoLFJhgZz6gWgVIPNzx3vBHyDB+HklqSkEhObcN6qtATMsvD2xAgMBAAECgYEAgQVg62GU5l8C4giEPBqKNNR5cGuMY1MjZBFJO8c07ouLENCxzNCxkVnVkRksSEBdyub68WnmAAIE1zFAIFpEpbqxzxJ0Kl4m1WBlTUcXOPo/5NI9L/P5O+j4TBNqpWZC+5TN/MBzexhrgNRFeGFal96t9QTe1eEOwvysvtVmUPkCQQDb9BM3UoyDN3yp3HZ1j014iAcy/TLVzmOZb8MJ6uEnV4vDQIoyCMj2aMIySxcZXU0dFGYQzFs7Uo4qbNkwUFfHAkEAmjNVNTqaHM/YdXIyAH8d4jZ+wNB7bPBcTDoe27Wsnuo+C50d+b+cB6f+4S8i8Q9MT2kpVmVZ3dRy55Tb3+vuxwJBAKge5nU5zpcZWVtIXO88qp1/c+lAaZPNHooQSAcTlieJHhYPBdJ6rojRx+XDSZOkoiWhCua6HN26G1pIOrZYIs8CQCwpQWDiLJrNx68zCjDsNtG/S6PK0V5MpBJMnuPLbumAKk7HK3uILZZfvXYeOsKQ4AjqFCWjFw6ZtmKuVh4WAqcCQQDDlWOuXo8bnfo447RaHyej2Q13kiXdXN0UW4ULJ2AHKp1O1iLXDLQjvNyqzKFTGis5L80E00LFlh+yeKfuufh3");
    }


    public static AutoLoginParam getAutoLoginParam(String rsaSignPrivateKey, String rsaEncryptPublicKey, String accessKey, String returnUrl, String userId, String extend, String version) throws Exception {

        AutoLoginParam autoLoginParam = new AutoLoginParam();

        autoLoginParam.setAccessKey(accessKey);
        autoLoginParam.setExtend(extend);
        autoLoginParam.setReturnUrl(returnUrl);
        autoLoginParam.setUid(userId);
        // Long timestamp = System.currentTimeMillis() - 15;
        Long timestamp = System.currentTimeMillis() / 1000 - 18;
        autoLoginParam.setTimestamp(timestamp + "");
        // autoLoginParam.setTimestamp(timestamp + "");
        // autoLoginParam.setTimestamp(DateUtil.offsetMinute(new Date(), 3).getTime() + "");

        //sign验证
        List<String> unsignedKeyList = new ArrayList<>();
        unsignedKeyList.add("version");
        unsignedKeyList.add("sign");

        // 获取验签sign
        // 1.将参数按照ASCII码从小到大的顺序排列并使用&符号拼接-s1
        String s1 = SignatureUtil.signString(autoLoginParam, unsignedKeyList);
        // 2.将s1使用"SHA-256"加密方式进行加密获取字符串-s2
        String s2 = ShaUtil.encrypt(s1, "SHA-256");
        // 3.将s2再使用验签私钥进行加密成为s3
        byte[] s2Rsa = RsaCoder.encryptByPrivateKey(s2.getBytes(StandardCharsets.UTF_8), rsaSignPrivateKey);
        // 4.将s3进行base64进行编码
        String sign = RsaCoder.encryptBASE64(s2Rsa);

        //
        autoLoginParam.setAccessKey(AutologinParamUtil.encryptParam(autoLoginParam.getAccessKey(), rsaEncryptPublicKey));

        if (StringUtils.hasText(autoLoginParam.getExtend())) {
            autoLoginParam.setExtend(AutologinParamUtil.encryptParam(autoLoginParam.getExtend(), rsaEncryptPublicKey));
        }

        autoLoginParam.setTimestamp(AutologinParamUtil.encryptParam(autoLoginParam.getTimestamp(), rsaEncryptPublicKey));

        if (StringUtils.hasText(autoLoginParam.getReturnUrl())) {
            autoLoginParam.setReturnUrl(AutologinParamUtil.encryptParam(URLEncoder.encode(autoLoginParam.getReturnUrl(), StandardCharsets.UTF_8), rsaEncryptPublicKey));
        }

        autoLoginParam.setUid(AutologinParamUtil.encryptParam(autoLoginParam.getUid(), rsaEncryptPublicKey));
        // 版本号和签名不再加密
        autoLoginParam.setVersion(version);
        autoLoginParam.setSign(sign);

        return autoLoginParam;
    }

}
